##package login

window.login = {}

( ->

##private

  $username_box = null
  $password_box = null
  $login_notification = null

  init_properties = ->
    $username_box = $('#unb')
    $password_box = $('#pwb')
    $login_notification = $('#lnt')

  #TODO: Change so this can be more easily updated with new languages
  get_language = (code) ->
    switch code
      when "jp" then return "Japanese"
      else return code

  load_data_from = (data) ->
    login.user = data.u
    login.real_name = data.r
    login.language = data.c[0].la
    login.language_name = get_language data.c[0].la
    login.class = data.c[0].cl

  update_strings = (realname, language) ->
    #TODO: Reload the page on logout
    #TODO: Get new seed on logout
    $('#djn').html languages[login.language].dojo_text
    $('#hzn').html languages[login.language].hall_text
    $('#un').html $('#un').html().replace "No Name", realname
    $('#langtoengrb').html "#{language} to English"
    $('#engtolangrb').html "English to #{language}"
    $('#spoktoengrb').html "Spoken #{language} to English"

  try_login = ->
    $('#lib').attr "disabled", "disabled"
    if $username_box.hasClass('cfb') or $password_box.hasClass('cfb') or
        $username_box.val() == '' or $password_box.val() == ''
      $login_notification.notify "create", { text: "You need to specify both a username and a password!" }
      return
    password_hash = sha256_digest sha256_digest($password_box.val()) + seed
    $.getJSON '/users/validate', { u: $username_box.val(), p: password_hash, s: seed }, (data) ->
      if data.e
        $login_notification.notify "create", {'text': data.e}
      else
        $('#to').fadeIn()
        load_data_from data
        grammar.load()
        login.get_vocab -> $('#to').fadeOut()
        $('#lw').fadeOut()
        #TODO: Untested!
        $.getJSON '/seeds/remove', { 's': cookie.get("s") }
        #TODO: Handle multiple classes and no classes
        $('#cl').html login.class
        $('#laf').attr "src", "/assets/app/flags/#{login.language}.png"
        app.input_methods[login.language].initialize() if app.input_methods[app.language]
        update_strings login.real_name, login.language_name
        #
        $('#mc').fadeIn()
        # TODO: Delete seed
    $('#lib').removeAttr "disabled"

##public

  # fn: function to run on completion
  login.get_vocab = (fn) ->
    login.vocab_request = $.getJSON '/vocabs', { l: login.language, c: login.class, u: login.user }, (v) ->
      vocab.clear()
      vocab.load login.language_name, v
      if v[0].pr
        app.reload_progress true, fn
      else
        app.reload_progress false, fn

##initialize

  login.initialize = ->
    init_properties()
    $('#lib').click -> try_login()
    $('.lbi').keypress (e) ->
      if e.keyCode == 13
        $('#lib')['click']()
        e.preventDefault()
        return false

##end

)()